#include "historydao.h"
#include <QSqlError>
#include <QDebug>
#include <QFile>
#include <QStandardPaths>
#include <QDir>

historydao &historydao::getInstance()
{
    static historydao instance;
    return instance;
}

bool historydao::savePlayHistory(int userId, const QString &musicName)
{
    if(!db.isOpen()) {
        if (!initDatabase()) {
            return false;
        }
    }
    QSqlQuery query(db);
    query.prepare("INSERT INTO play_history (user_id, music_name, play_time) "
                  "VALUES (:user_id, :music_name, :play_time)");
    query.bindValue(":user_id", userId);
    query.bindValue(":music_name", musicName);
    query.bindValue(":play_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    if (!query.exec()) {
        qDebug() << "保存播放记录失败：" << query.lastError().text();
        return false;
    }
    return true;
}

QList<PlayHistoryRecord> historydao::getPlayHistory(int userId, int limit)
{
    QList<PlayHistoryRecord> historyList;
    if (!db.isOpen()) {
        if (!initDatabase()) {
            return historyList;
        }
    }

    QSqlQuery query(db);
    query.prepare("SELECT music_name, play_time FROM play_history "
                  "WHERE user_id = :user_id "
                  "ORDER BY play_time DESC "
                  "LIMIT :limit");
    query.bindValue(":user_id", userId);
    query.bindValue(":limit", limit);

    if (query.exec()) {
        while (query.next()) {
            PlayHistoryRecord record;
            record.musicName = query.value(0).toString();
            record.playTime = query.value(1).toString();
            historyList.append(record);
        }
    } else {
        qDebug() << "获取播放历史失败：" << query.lastError().text();
    }
    return historyList;
}


historydao::historydao()
{
    dbName = "playerdb.db";
    // 初始化数据库
    initDatabase();
    // 初始化历史记录表
    initHistoryTable();
}

historydao::~historydao()
{
    if(db.isOpen())
    {
        db.close();
    }
}

bool historydao::initDatabase()
{
    // 添加SQLite数据库驱动
    db = QSqlDatabase::addDatabase("QSQLITE", "history_connection");
    db.setDatabaseName(dbName);
    // 打开数据库
    if (!db.open()) {
        qDebug() << "数据库打开失败：" << db.lastError().text();
        return false;
    }
    return true;
}

// 创建历史记录表
void historydao::initHistoryTable() {
    if (!db.isOpen()) {
        if (!initDatabase()) {
            return;
        }
    }

    QSqlQuery query(db);
    // 创建播放历史表
    QString createSql = "CREATE TABLE IF NOT EXISTS play_history ("
                       "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                       "user_id INTEGER NOT NULL, "
                       "music_name TEXT NOT NULL, "
                       "play_time DATETIME NOT NULL, "
                       "FOREIGN KEY(user_id) REFERENCES user(id)"
                       ");";
    if (!query.exec(createSql)) {
        qDebug() << "创建播放历史表失败：" << query.lastError().text();
    }
}

